package com.force.abril.booking.download.transformer;

import static com.force.abril.booking.download.transformer.ExecutiveBookingFieldMapping.FIELDS;

import static com.topi.integration.connectorapi.transformer.XmlObjectHelper.*;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtilsBean2;
import org.springframework.stereotype.Component;

import br.com.abril.booking.ExecutiveBooking;

import com.force.abril.transformer.Mapping;
import com.sforce.soap.partner.sobject.SObject;
import com.sforce.ws.bind.XmlObject;

@Component
public class ExecutiveBookingTransformer {
	
	

	public List<ExecutiveBooking> toBookingsFromSObject(SObject[] sfBookings) {
		List<ExecutiveBooking> bookings = new ArrayList<ExecutiveBooking>();
		for (SObject sfBooking : sfBookings) {
			bookings.add(toLocalBooking(sfBooking));
		}
		return bookings;
	}

	public ExecutiveBooking toLocalBooking(SObject salesForceRow) {

		ExecutiveBooking booking = new ExecutiveBooking();

		XmlObject sfBooking = (XmlObject) salesForceRow.getField("Reserva__r");
		XmlObject sfProduct = (XmlObject) sfBooking.getField("Produto__r");
		XmlObject sfAdvertiser = (XmlObject) sfBooking.getField("AnuncianteMigrado__r");
		XmlObject sfOffice = (XmlObject) sfBooking.getField("AgenciaMigrada__r");

		booking.setDataReserva( getStringField(sfBooking,"DataDaReserva__c"));
		booking.setOffice     ( getStringField(sfBooking,"AgenciaMigrada__c") );
		booking.setAdvertiser ( getStringField(sfBooking,"AnuncianteMigrado__c") );
		booking.setProduct    ( getStringField(sfBooking,"Produto__c") );
		
		booking.setUn         ( getStringField(sfBooking,"UN__c") );
		
		booking.setProductGroup( getStringField(sfProduct,"GrupoDeProduto__c") );
		booking.setProductId( getStringField(sfProduct,"IDProduto__c") );

		booking.setAdvertiserId( getStringField(sfAdvertiser,"IDSistema__c") );
		booking.setOfficeId( getStringField(sfOffice,"IDSistema__c") );
		
		booking.defineWallet();
		
		for (Mapping mapping : FIELDS) {

			try {

				BeanUtilsBean2.getInstance().setProperty(booking,
						mapping.getKey(),
						salesForceRow.getField(mapping.getValue()));

			} catch (IllegalAccessException e) {
				e.printStackTrace();

			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}

		}

		return booking;

	}

}
